<template>
  <div class="app-container">
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px" class="find">
        <el-form-item label="渠道名称" prop="channelName">
          <el-input
            v-model="queryParams.channelName"
            placeholder="请输入渠道名称"
            clearable
            @keyup.enter="handleQuery"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="渠道状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="渠道状态" clearable style="width: 200px">
            <el-option label="正常" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="渠道类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="渠道类型" clearable style="width: 200px">
            <el-option label="线上渠道" value="1" />
            <el-option label="线下渠道" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="dateRange"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 240px; margin-right: 12px;"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery" :loading="loading">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery" :disabled="loading">重置</el-button>
        </el-form-item>
      </el-form>

      
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate">修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="info" plain icon="Upload" @click="handleImport">导入</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="tableData" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="渠道编号" prop="channelId" width="100" />
        <el-table-column label="渠道名称" prop="channelName" :show-overflow-tooltip="true" />
        <el-table-column label="渠道类型" prop="type" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.type === 2 ? 'success' : ''">{{ scope.row.type === 1 ? '线上渠道' : '线下渠道' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="渠道状态" prop="status" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">{{ scope.row.status === 1 ? '正常' : '禁用' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建人" prop="createBy" width="100" />
        <el-table-column label="创建时间" prop="createTime" width="180" />
        <el-table-column label="备注信息" prop="remark" :show-overflow-tooltip="true" />
        <el-table-column label="操作" width="150" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        v-model:page="pageNum"
        v-model:limit="pageSize"
        @pagination="handlePagination"
      />

      <!-- 添加或修改渠道对话框 -->
      <el-dialog :title="title" v-model="open" width="500px" append-to-body>
        <el-form ref="channelRef" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="渠道名称" prop="channelName">
            <el-input v-model="form.channelName" placeholder="请输入渠道名称" />
          </el-form-item>
          <el-form-item label="渠道状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio label="1">正常</el-radio>
              <el-radio label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="渠道类型" prop="type">
            <el-radio-group v-model="form.type">
              <el-radio label="1">线上渠道</el-radio>
              <el-radio label="2">线下渠道</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="备注信息" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </template>
      </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { listChannel, delChannel, addChannel, getChannel, updateChannel, exportChannel } from '@/api/tienchin/channel';
import Pagination from '@/components/Pagination/index.vue';
import RightToolbar from '@/components/RightToolbar/index.vue';
import { download } from '@/utils/request';

const queryRef = ref(null);
const channelRef = ref(null); // 新增的表单ref
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRange = ref([]);
const pageNum = ref(1);
const pageSize = ref(10);

// 模态框相关数据
const open = ref(false);
const title = ref('');

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  channelName: undefined,
  status: undefined,
  type: undefined,
});

const form = reactive({
  channelId: undefined,
  channelName: undefined,
  status: '',
  type: '',
  remark: undefined,
});

const rules = reactive({
  channelName: [{ required: true, message: "渠道名称不能为空", trigger: "blur" }],
  status: [{ required: true, message: "渠道状态不能为空", trigger: "change" }],
  type: [{ required: true, message: "渠道类型不能为空", trigger: "change" }],
});

const tableData = ref([]);

const getList = () => {
  loading.value = true;
  
  // 构建查询参数
  const params = {
    pageNum: queryParams.pageNum,
    pageSize: queryParams.pageSize,
  };

  // 添加搜索条件，只传递有值的参数
  if (queryParams.channelName && queryParams.channelName.trim()) {
    params.channelName = queryParams.channelName.trim();
  }
  
  if (queryParams.status !== undefined && queryParams.status !== '') {
    params.status = queryParams.status;
  }
  
  if (queryParams.type !== undefined && queryParams.type !== '') {
    params.type = queryParams.type;
  }

  // 添加日期范围参数，使用params[beginTime]和params[endTime]格式
  if (dateRange.value && dateRange.value.length === 2) {
    params['params[beginTime]'] = dateRange.value[0];
    params['params[endTime]'] = dateRange.value[1];
  }

  listChannel(params).then(response => {
    if (response.code === 200) {
      tableData.value = response.rows;
      total.value = response.total;
    } else {
      ElMessage.error(response.msg || '获取数据失败');
    }
    loading.value = false;
  }).catch(error => {
    console.error('获取渠道列表失败:', error);
    ElMessage.error('获取数据失败');
    loading.value = false;
  });
};

const handleQuery = () => {
  queryParams.pageNum = 1;
  pageNum.value = 1;
  getList();
};

const resetQuery = () => {
  // 重置表单字段
  queryRef.value.resetFields();
  
  // 重置日期范围
  dateRange.value = [];
  
  // 重置分页参数到第一页
  queryParams.pageNum = 1;
  queryParams.pageSize = 10;
  pageNum.value = 1;
  pageSize.value = 10;
  
  // 不触发网络请求，只清空搜索条件
};

const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.channelId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

// 表单重置
const reset = () => {
  form.channelId = undefined;
  form.channelName = undefined;
  form.status = '';
  form.type = '';
  form.remark = undefined;
  if (channelRef.value) {
    channelRef.value.resetFields();
  }
};

const handleAdd = () => {
  reset();
  console.log(form);
  open.value = true;
  title.value = "新增渠道";
};

const handleUpdate = (row) => {
  reset();
  const channelId = row.channelId || ids.value;
  getChannel(channelId).then(response => {
    Object.assign(form, response.data); // 填充表单数据
    form.status = String(form.status); // 确保radio绑定的是字符串
    form.type = String(form.type); // 确保radio绑定的是字符串
    open.value = true;
    title.value = "修改渠道";
  }).catch(error => {
    ElMessage.error('获取渠道详情失败');
    console.error('获取渠道详情失败:', error);
  });
};

const submitForm = () => {
  channelRef.value.validate(valid => {
    if (valid) {
      const dataToSend = { ...form }; // 创建浅拷贝

      // 确保status和type字段为数字类型，并移除不应由前端提交的字段
      if (dataToSend.status !== undefined && dataToSend.status !== '') {
        dataToSend.status = Number(dataToSend.status);
      }
      if (dataToSend.type !== undefined && dataToSend.type !== '') {
        dataToSend.type = Number(dataToSend.type);
      }
      if (dataToSend.createTime) {
        delete dataToSend.createTime;
      }
      if (dataToSend.updateTime) {
        delete dataToSend.updateTime;
      }

      if (dataToSend.channelId != undefined) {
        updateChannel(dataToSend).then(response => {
          ElMessage.success("修改成功");
          open.value = false;
          getList();
        }).catch(error => {
          ElMessage.error("修改失败");
          console.error("修改失败:", error);
        });
      } else {
        addChannel(dataToSend).then(response => {
          ElMessage.success("新增成功");
          open.value = false;
          getList();
        }).catch(error => {
          ElMessage.error("新增失败");
          console.error("新增失败:", error);
        });
      }
    }
  });
};

const cancel = () => {
  open.value = false;
  reset();
};

const handleDelete = (row) => {
  const channelIds = row.channelId || ids.value;
  ElMessageBox.confirm('是否确认删除渠道编号为"' + channelIds + '"的数据项?', "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(function() {
    return delChannel(channelIds);
  }).then(() => {
    getList();
    ElMessage.success("删除成功");
  }).catch(() => {});
};

const handleImport = () => {
  console.log('导入');
};

const handleExport = () => {
  // 构建导出参数，包含当前的分页和搜索条件
  const params = {
    pageNum: queryParams.pageNum,
    pageSize: queryParams.pageSize,
  };

  // 添加搜索条件，只传递有值的参数
  if (queryParams.channelName && queryParams.channelName.trim()) {
    params.channelName = queryParams.channelName.trim();
  }
  
  if (queryParams.status !== undefined && queryParams.status !== '') {
    params.status = queryParams.status;
  }
  
  if (queryParams.type !== undefined && queryParams.type !== '') {
    params.type = queryParams.type;
  }

  // 添加日期范围参数
  if (dateRange.value && dateRange.value.length === 2) {
    params['params[beginTime]'] = dateRange.value[0];
    params['params[endTime]'] = dateRange.value[1];
  }

  // 使用request工具中的download方法
  download('/tienchin/channel/export', params, '渠道数据.xlsx');
};

// 分页处理函数
const handlePagination = (pagination) => {
  queryParams.pageNum = pagination.page;
  queryParams.pageSize = pagination.limit;
  pageNum.value = pagination.page;
  pageSize.value = pagination.limit;
  getList();
};

onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.find {
  .el-form-item {
    margin-bottom: 16px;
    margin-right: 16px;
    
    &:last-child {
      margin-right: 0;
    }
  }
}

.mb8 {
  margin-bottom: 8px;
}

// 表格样式优化
.el-table {
  margin-top: 16px;
}

// 分页样式
.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>